package com.nie.mybatisPlus.generator.system.config;

import cn.hutool.core.util.StrUtil;
import com.nie.mybatisPlus.generator.system.context.BaseContextHandler;
import com.nie.mybatisPlus.generator.system.exception.BizException;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 租户上下文处理程序拦截器
 *
 * @author nie_cq
 * @date 2022/11/19
 */
@Slf4j
@NoArgsConstructor
@Component
public class TenantContextHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String tenantId = request.getHeader("tenantId");
        if (StrUtil.isBlank(tenantId)) {
            throw  BizException.TENANT_IS_NULL;
        }
        BaseContextHandler.setTenant(tenantId);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContextHandler.clear();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
